package com.linkgie.galaxyframework.persistence.mongodb;

import org.springframework.data.mongodb.core.MongoTemplate;

import com.linkgie.galaxyframework.utils.service.ServiceContext;

public class MongoPersistence {

    private static MongoPersistenceDriverSPI DRIVER_SPI;

    /**
     * 获取指定持久化对象的存储集合名称；
     * 
     * @param poClazz
     * @return
     */
    public static String getCollectionName(Class<?> poClazz) {
        return getDriver().getCollectionName(poClazz);
    }

    public static MongoTemplate getMongoTemplate() {
        return getDriver().getMongoTemplate();
    }


    private static MongoPersistenceDriver getDriver() {
        if (DRIVER_SPI == null) {
            lookupDriverSPI();
        }
        return DRIVER_SPI.getDriver();
    }

    private synchronized static MongoPersistenceDriverSPI lookupDriverSPI() {
        if (DRIVER_SPI != null) {
            return DRIVER_SPI;
        }
        ServiceContext<MongoPersistenceDriverSPI> serviceContext = ServiceContext
                .load(MongoPersistenceDriverSPI.class);
        if (serviceContext.getSize() == 0) {
            throw new IllegalStateException("No MongoPersistenceDriverSPI found.");
        }
        if (serviceContext.getSize() > 1) {
            throw new IllegalStateException("More than one MongoPersistenceDriverSPI found.");
        }
        DRIVER_SPI = serviceContext.getFirstService();
        return DRIVER_SPI;
    }

}
